package com.gxuwz.stats.service.excelNewHandler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.IntellectualProperty;
import com.gxuwz.stats.entity.dto.IntellectualPropertyPatentDTO;
import com.gxuwz.stats.service.excelhandler.ImportResultProvider;
import com.gxuwz.stats.service.impl.IntellectualPropertyServiceImpl;

import java.util.ArrayList;
import java.util.List;

public class IntellectualPropertyPatentListener extends AnalysisEventListener<IntellectualPropertyPatentDTO> implements ImportResultProvider {
    private final List<IntellectualProperty> dataList = new ArrayList<>();
    private int ignoredCount = 0;
    private final IntellectualPropertyServiceImpl workloadService;
    private boolean stopProcessing = false;

    private final String currentUsername;
    private final String currentRole;
    private final String currentDepartment;

    public IntellectualPropertyPatentListener(IntellectualPropertyServiceImpl workloadService, String username, String role, String department) {
        this.workloadService = workloadService;
        this.currentUsername = username;
        this.currentRole = role;
        this.currentDepartment = department;
    }

    @Override
    public void invoke(IntellectualPropertyPatentDTO dto, AnalysisContext context) {
        if (stopProcessing) return;
        if (dto.getUsername() == null || dto.getUsername().trim().isEmpty()) return;
        if (dto.getUsername().contains("说明") || dto.getUsername().length() > 12) {
            stopProcessing = true;
            return;
        }
        if ("普通用户".equals(currentRole)) {
            if (!dto.getUsername().equals(currentUsername)) {
                ignoredCount++;
                return;
            }
        }
        // DTO转实体
        IntellectualProperty entity = new IntellectualProperty();
        entity.setUsername(dto.getUsername());
        entity.setIntellectualAchievementName(dto.getIntellectualAchievementName());
        entity.setAuthorizationNumber(dto.getAuthorizationNumber());
        entity.setIntellectualCategory(dto.getIntellectualCategory());
        entity.setIntellectualYear(dto.getIntellectualYear());
        dataList.add(entity);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        workloadService.saveAllFromDTO(dataList);
    }

    @Override
    public int getImportedCount() { return dataList.size(); }
    @Override
    public int getIgnoredCount() { return ignoredCount; }
}
